// @/api/chat.ts

import { defineFakeRoute } from 'vite-plugin-fake-server/client'
import dayjs from 'dayjs'

export default defineFakeRoute([
  {
    url: '/llm/models',
    method: 'get',
    response: () => {
      return {
        success: true,
        message: '操作成功',
        data: [
          {
            modelKey: 'qwen3:8b',
            displayName: 'qwen3:8b',
          },
          {
            modelKey: 'deepseek-r1:8b',
            displayName: 'deepseek-r1:8b',
          },
        ],
      }
    },
  },
  {
    url: '/llm/chat/generate',
    method: 'post',
    response: ({ body }) => {
      return {
        success: true,
        message: '操作成功',
        data: {
          model: body.model,
          content: 'New Title from Mock',
          usage: {
            prompt_tokens: 0,
            completion_tokens: 0,
            total_tokens: 0,
          },
          create_at: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        },
      }
    },
  },
  {
    url: '/llm/chat/completions',
    method: 'post',
    headers: {
      'Content-Type': 'text/event-stream',
    },
    response: async ({ body }, _req, res) => {
      // 这里模拟了一段返回
      const response =
        'Hello! This message was anwsered from vite-plugin-fake-server. You can visit `/src/config/llmProvider/backend.ts` and `/mock/chat.ts` to view detail, thx.'
      // 封装data生成
      const pushData = (word: string): string => {
        return (
          `data: {"id":"chatcmpl-mock","object":"chat.completion.chunk","created":${new Date().getTime()},"model":"${body.model}","system_fingerprint":"${body.model}","choices":[{"index":0,"delta":{"role":"assistant","content":"${word}"},"logprobs":null,"finish_reason":null}]}` +
          '\n'
        )
      }
      // 响应数据
      // 这里通过判断res是否存在来判断开启stream模式
      // 打包模式下 enableProd，res是undefined，因此不支持流输出
      if (res && body.stream) {
        // 模拟stream模式
        for (const word of response) {
          res.write('event: message\n')
          res.write(pushData(word) + '\n')
          // 模拟一段延迟
          await new Promise((resolve) => setTimeout(resolve, 50))
        }
        res.write('data: [DONE]')
      } else {
        // 模拟非stream模式
        const datas = ['event: message\n']
        datas.push(pushData(response) + '\n')
        return datas.join('\n') + 'data: [DONE]'
      }
    },
  },
])
